package com.camp.android.trip.n.track;

import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.camp.android.trip.n.track.R;
import com.camp.android.trip.n.track.trip.TripItineraryActivity;

public class NewTripActivity extends Activity {
	
	public boolean isEdit;
	public int tripid;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_trip);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        Intent intent = getIntent();
        String trip_id = intent.getStringExtra("trip_id");
        if(!(trip_id == null)){
        	isEdit = true;
        	// populate fields 
        	int id = Integer.parseInt(trip_id);
        	tripid = id;
        	Trip trip = new DatabaseManager(this).getTripById(id);
        	((TextView) findViewById(R.id.trip_name_text)).setText(trip.name);
        	setTitle(trip.name);
        	((TextView) findViewById(R.id.city_area_text)).setText(trip.city);
        	((DatePicker) findViewById(R.id.start_date_picker)).updateDate(trip.start.get(Calendar.YEAR), 
        			trip.start.get(Calendar.MONTH), trip.start.get(Calendar.DAY_OF_MONTH));
        	((DatePicker) findViewById(R.id.end_date_picker)).updateDate(trip.end.get(Calendar.YEAR), 
        			trip.end.get(Calendar.MONTH), trip.end.get(Calendar.DAY_OF_MONTH));
        } else {
        	isEdit = false;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_new_trip, menu);
        return true;
    }

    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {

        View v = getCurrentFocus();
        boolean ret = super.dispatchTouchEvent(event);

        if (v instanceof EditText) {
            View w = getCurrentFocus();
            int scrcoords[] = new int[2];
            w.getLocationOnScreen(scrcoords);
            float x = event.getRawX() + w.getLeft() - scrcoords[0];
            float y = event.getRawY() + w.getTop() - scrcoords[1];

            Log.d("Activity", "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+scrcoords[1]);
            if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) { 

                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
            }
        }
    return ret;
    }
    
    public void create(View view){
    	// get user entered info
    	String name = ((TextView) findViewById(R.id.trip_name_text)).getText().toString();
    	String city = ((TextView) findViewById(R.id.city_area_text)).getText().toString();
    	DatePicker startDate = ((DatePicker) findViewById(R.id.start_date_picker));
    	Calendar start = Calendar.getInstance();
    	start.set(
    			startDate.getYear(),startDate.getMonth(),startDate.getDayOfMonth());
    	DatePicker endDate = ((DatePicker) findViewById(R.id.end_date_picker));
    	Calendar end = Calendar.getInstance();
    	end.set(
    			endDate.getYear(),endDate.getMonth(),endDate.getDayOfMonth());
    	// create new Trip object
    	Trip trip = new Trip(name,city,start,end);
    	int id;
    	if(isEdit){
    		id = tripid;
    		new DatabaseManager(this).updateTrip(trip);
    	} else {
    		id = addToDb(trip); // add to db and return its id
    	}
    	Intent intent = new Intent(this, TripItineraryActivity.class);
    	intent.putExtra("trip_id", Integer.toString(id));
    	// TODO add trip id to intent
		startActivity(intent); // open trip page
    }

    public int addToDb(Trip trip){
    	DatabaseManager db = new DatabaseManager(this);
    	int id = db.addTrip(trip);
    	Log.i("TT","added trip to db " + trip.name + " id = " + id);
    	return id;
    	
    }

}
